<template>
  <div class="w-full">
    <el-upload
      :action="fileUploadUrl"
      :headers="uploadHeaders"
      :accept="accept"
      :before-upload="beforeUpload"
      :on-success="onSuccess"
      :on-progress="(event: any, file: any) => (progressFile = file)"
      :on-error="onError"
      :show-file-list="false"
      :disabled="disabled"
      multiple
      drag
    >
      {{ $t('cms.clickOrDragToUpload') }}
      <!-- <el-button type="primary">{{ $t('cms.clickToUpload') }}</el-button> -->
    </el-upload>
    <el-progress
      v-if="progressFile.status === 'uploading'"
      :percentage="parseInt(progressFile.percentage, 10)"
    />
    <transition-group
      tag="ul"
      :class="['el-upload-list', 'el-upload-list--text', { 'is-disabled': disabled }]"
      name="el-list"
    >
      <li v-for="file in fileList" :key="file.url" class="el-upload-list__item is-success">
        <a class="el-upload-list__item-name" @click="() => handlePreview(file)">
          <el-icon class="el-icon--document"><Document /></el-icon>{{ file.name }}
        </a>
        <label class="el-upload-list__item-status-label">
          <el-icon class="el-icon--upload-success el-icon--circle-check"><CircleCheck /></el-icon>
        </label>
        <el-icon
          v-if="!disabled"
          class="el-icon--close"
          @click="() => fileList.splice(fileList.indexOf(file), 1)"
          ><Close
        /></el-icon>
      </li>
    </transition-group>
    <el-dialog
      v-model="previewVisible"
      :title="$t('cms.content.attachs.attr')"
      top="5vh"
      :width="768"
      append-to-body
    >
      <el-form ref="form" :model="previewFile" label-width="150px">
        <el-form-item
          prop="name"
          :label="$t('name')"
          :rules="{ required: true, message: () => $t('common.required') }"
        >
          <el-input v-model="previewFile.name" maxlength="100" />
        </el-form-item>
        <el-form-item
          prop="size"
          :label="$t('size')"
          :rules="{ required: true, message: () => $t('common.required') }"
        >
          <el-input v-model="previewFile.size" maxlength="19">
            <template #append>Byte</template>
          </el-input>
        </el-form-item>
        <el-form-item
          prop="url"
          label="URL"
          :rules="{ required: true, message: () => $t('common.required') }"
        >
          <el-input v-model="previewFile.url" maxlength="255" />
        </el-form-item>
        <el-button type="primary" native-type="submit" @click.prevent="() => handleSubmit()">{{
          $t('common.save')
        }}</el-button>
      </el-form>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, toRefs, computed, watch } from 'vue'
import { ElMessage, useFormItem } from 'element-plus'
import { Close, Document, CircleCheck } from '@element-plus/icons-vue'
import { useI18n } from 'vue-i18n'
import { getAccessToken, getTenantId } from '@/utils/auth'
import { getSiteHeader } from '@/utils/cmscommon'
import { uploadSettings, fileUploadUrl } from '@/api/cms/upload/types'

const props = defineProps({
  modelValue: { type: Array, default: () => [] },
  fileAccept: { type: String, default: null },
  fileMaxSize: { type: Number, default: null },
  disabled: { type: Boolean, default: false }
})
const emit = defineEmits({ 'update:modelValue': null })

const { fileAccept, fileMaxSize } = toRefs(props)
const { t } = useI18n()
const { modelValue } = toRefs(props)
const progressFile = ref<any>({})
const uploadHeaders = ref()

const fileList = computed({
  get: (): any[] => {
    return modelValue.value
  },
  set: (val) => emit('update:modelValue', val)
})
const { formItem } = useFormItem()
watch(
  fileList,
  () => {
    formItem?.validate?.('change').catch((err: any) => {
      if (import.meta.env.MODE !== 'production') {
        console.warn(err)
      }
    })
  },
  { deep: true }
)
const previewVisible = ref<boolean>(false)
const previewFile = ref<any>({})
const form = ref<any>()

const handlePreview = (file: any) => {
  previewFile.value = file
  previewVisible.value = true
}
const handleSubmit = () => {
  form.value.validate(async (valid: boolean) => {
    if (!valid) return
    previewVisible.value = false
  })
}
const accept = computed(() => fileAccept?.value ?? uploadSettings.attachInputAccept)
const maxSize = computed(() => fileMaxSize?.value ?? uploadSettings.fileLimitByte)
const beforeUpload = (file: any) => {
  if (maxSize.value > 0 && file.size > maxSize.value) {
    ElMessage.error(t('cms.error.fileMaxSize', { size: `${maxSize.value / 1024 / 1024} MB` }))
    return false
  }
  uploadHeaders.value = {
    Authorization: 'Bearer ' + getAccessToken(),
    'tenant-id': getTenantId(),
    'jprocms-site-id': getSiteHeader()
  }
  return true
}
const onError = (error: Error) => {
  ElMessage.error(t('上传失败，请您重新上传！'))
  console.log(error)
}
const onSuccess = (res: any) => {
  if (res.code == 0) {
    fileList.value.push({ name: res.data.name, url: res.data.url, size: res.data.size })
  } else {
    ElMessage.error(t('上传失败，请您重新上传！错误原因 ', res.msg))
    console.log(res.msg)
  }
}
</script>
<style lang="scss" scoped>
:deep(.el-upload-dragger) {
  @apply bg-primary-lighter text-primary;

  padding: 0 20px;
}
</style>
